package app.caihan.wanandroid.ui.wxarticle

import android.os.Bundle
import androidx.lifecycle.Observer
import app.caihan.scframe.databind.DataBindingConfig
import app.caihan.scframe.ktx.setSingleOnItemClickListener
import app.caihan.scframe.util.StatusBarConfig
import app.caihan.wanandroid.BR
import app.caihan.wanandroid.R
import app.caihan.wanandroid.base.WanBaseFragment


class ChapterFragment : WanBaseFragment<ChapterFragmentModel>() {

    private val chaptersId by lazy { arguments?.getInt(CID) }

    companion object {
        private const val CID = "ChaptersId"
        fun newInstance(cid: Int): ChapterFragment {
            val fragment = ChapterFragment()
            val bundle = Bundle()
            bundle.putInt(CID, cid)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val mAdapter by lazy { ChapterListAdapter() }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(BR.vm).addBindingParam(BR.adapter, mAdapter)
    }

    override fun bindLayoutId(): Int {
        return R.layout.fragment_chapter_list
    }

    override fun getStatusBarConfig(): StatusBarConfig? {
        return null
    }

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun lazyLoadData() {
        chaptersId?.let {
            mViewModel.autoRefresh(it)
        }
    }

    override fun createObserver() {
        mAdapter.apply {
            setSingleOnItemClickListener { adapter, view, position ->
                val item = mAdapter.data[position]
                toast("点击了${item.author} 的 ${item.title}")
            }
        }
        mViewModel.apply {
            chapterArticleList.observe(this@ChapterFragment, Observer {
                if (it.curPage == 1) {
                    mAdapter.setNewInstance(it.datas.toMutableList())
                } else {
                    mAdapter.addData(it.datas.toMutableList())
                }
            })
        }
    }

}